package com.cangxuan.app.ui.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import android.view.ViewTreeObserver;
import android.widget.*;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.DB;
import com.cangxuan.app.MainActivity;
import com.cangxuan.app.R;
import com.cangxuan.app.adapter.HomeCollectionListAdapter;
import com.cangxuan.app.adapter.HomeSaleCalendarAdapter;
import com.cangxuan.app.entity.Collections;
import com.cangxuan.app.entity.Goods;
import com.cangxuan.app.ui.AnnouncementsActivity;
import com.cangxuan.app.ui.user.ArticleContentActivity;
import com.cangxuan.app.utils.DBUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.cangxuan.app.utils.ListViewUtils;
import com.google.android.material.tabs.TabLayout;

import java.io.File;
import java.net.HttpURLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 首页fragment
 * author：何程城
 */
public class HomeFragment extends Fragment {
    Handler handler = new Handler();

    TabLayout tabLayout; // 内容切换标签
    private MyPagerAdapter myPagerAdapter;
    private ViewPager viewPager; // 轮播图区域
    private LinearLayout viewGroup;
    // swiper配置
    private int currentItem = 0;
    private static final int CAROUSEL_TIME = 3000;
    View parentView;
    ScrollView homeScrollView;
    // 搜索框
    TextView homeSearchInput;
    LinearLayout homeBtn1;
    ListView homeListView;
    ListView homeListView1;
    LinearLayout loading;
    HomeCollectionListAdapter homeCollectionListAdapter;
    HomeSaleCalendarAdapter homeSaleCalendarAdapter;
    List<Collections> collectionsList = new ArrayList<>();
    List<Collections> collectionCalendar = new ArrayList<>();
    int cListPageIndex = 1;
    int cCalendarPageIndex = 1;
    boolean listFinish = false;
    boolean calendarFinish = false;
    boolean loadingIsShow = false;
    int currentTitle = 0;
    boolean collectionInit = false;
    boolean bannerInit = false;
    TextView newNoticeText;
    TextView textNews;
    LinearLayout newNotice;
    ConstraintLayout newNewsBox;
    int newNoticeId;
    int newNewsId;
    boolean swiperInit = false;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (parentView == null) {
            parentView = inflater.inflate(R.layout.fragment_home, container, false);
            tabLayout = parentView.findViewById(R.id.homeListTitle); // 首页分页标签
            homeListView = parentView.findViewById(R.id.homeListView);
            homeListView1 = parentView.findViewById(R.id.homeListView1);
            loading = parentView.findViewById(R.id.loading);
            homeScrollView = parentView.findViewById(R.id.homeScrollView);
            viewPager = parentView.findViewById(R.id.viewPager); // 轮播图
            viewGroup = parentView.findViewById(R.id.viewGroup); // 轮播图分页器
            homeSearchInput = parentView.findViewById(R.id.homeSearchInput);
            homeBtn1 = parentView.findViewById(R.id.home_btn1); //公告按钮
            newNoticeText = parentView.findViewById(R.id.newNoticeText); //最新公告
            newNewsBox = parentView.findViewById(R.id.newNewsBox); //最新新闻
            newNotice = parentView.findViewById(R.id.newNotice); //最新新闻
            textNews = parentView.findViewById(R.id.textNews); //最新新闻

            newNewsBox.setOnClickListener(view -> {
                Intent intent = new Intent();
                intent.setClass(getContext(), ArticleContentActivity.class);
                intent.putExtra("id", newNewsId);
                startActivity(intent);
            });
            homeSearchInput.setOnClickListener(view -> {
                Bundle bundle = new Bundle();
                bundle.putBoolean("search", true);
                setArguments(bundle);
                MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.navController.navigate(R.id.action_HomeFragment_to_MarketFragment, bundle);
            });
            homeBtn1.setOnClickListener(view -> {
                Intent intent = new Intent();
                intent.setClass(getContext(), AnnouncementsActivity.class);
                startActivity(intent);
            });
            newNotice.setOnClickListener(view -> {
                Intent intent = new Intent();
                intent.setClass(getContext(), ArticleContentActivity.class);
                intent.putExtra("id", newNoticeId);
                startActivity(intent);
            });
            loading.setVisibility(View.GONE);
            homeCollectionListAdapter = new HomeCollectionListAdapter(collectionsList, getContext());
            homeListView.setAdapter(homeCollectionListAdapter);
            ListViewUtils.setListViewHeightBasedOnChildren(homeListView);
            homeSaleCalendarAdapter = new HomeSaleCalendarAdapter(collectionCalendar, getContext());
            homeListView1.setAdapter(homeSaleCalendarAdapter);

            homeScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {
                    int scrollY = homeScrollView.getScrollY();
                    int scrollViewHeight = homeScrollView.getHeight();
                    // 获取 ScrollView 内容的高度
                    View contentView = homeScrollView.getChildAt(0);
                    int contentHeight = contentView.getHeight();

                    // 判断是否滚动到底部
                    if (scrollY + scrollViewHeight >= contentHeight) {
                        if (!isHandlingScroll) {
                            isHandlingScroll = true;
                            handler.removeCallbacks(scrollRunnable);
                            handler.postDelayed(scrollRunnable, 200); // 延迟处理滚动事件，单位为毫秒
                        }
                    } else {
                        handler.removeCallbacks(scrollRunnable);
                        isHandlingScroll = false;
                    }
                }
            });
            getNewNotice();
            getNewNews();
            // 初始化标签页
            initTabs();
            initSwiper();
            getBannerData();

        }
        return parentView;
    }

    private final Runnable mTicker = new Runnable() {
        @Override
        public void run() {
            long now = SystemClock.uptimeMillis();
            // 等同于
            long next = now + CAROUSEL_TIME;
            // 回调应该运行的绝对时间 3秒后发送消息
            handler.postAtTime(mTicker, next);
            currentItem++;
            viewPager.setCurrentItem(currentItem);
        }
    };
    private boolean isHandlingScroll = false;
    private Runnable scrollRunnable = new Runnable() {
        @Override
        public void run() {
            // 处理滚动到底部的逻辑
            if (currentTitle == 0) {
                if (!loadingIsShow) {
                    loadingIsShow = true;
                    initCollectionList(homeCollectionListAdapter);
                }
            } else if (currentTitle == 1) {
                if (!loadingIsShow) {
                    loadingIsShow = true;
                    initCalendarList(homeSaleCalendarAdapter);
                }
            }
            loadingIsShow = true;
//            initCollectionList(homeCollectionListAdapter);
            isHandlingScroll = false;
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        handler.postDelayed(mTicker, CAROUSEL_TIME);
    }

    @Override
    public void onStop() {
        super.onStop();
        handler.removeCallbacks(mTicker);
    }

    public List<String> banners;

    /**
     * 首页swiper的Adapter
     */
    class MyPagerAdapter extends PagerAdapter {
        private Context context;
        private View.OnClickListener onBannerClickListener;
        private static final String TAG = "MyPagerAdapter";

        public MyPagerAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            //返回int的最大值 可以一直滑动
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= banners.size();
            ImageView imageView = new ImageView(context);
            //设置图片缩放类型
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            //把当前的下标通过setTag方法设置进去
            imageView.setTag(position);
            imageView.setImageBitmap(BitmapFactory.decodeFile(banners.get(position)));
            imageView.setOnClickListener(onClickListener);
//            imageView.setAdjustViewBounds(true);
            container.addView(imageView);
            return imageView;
        }

        private View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBannerClickListener.onClick(v);
            }
        };

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        public void setOnBannerClickListener(View.OnClickListener onBannerClickListener) {
            this.onBannerClickListener = onBannerClickListener;
        }

        public List<String> getBanners() {
            return banners;
        }
    }

    public void initSwiper() {
        banners = new ArrayList<>();
        Cursor data = DBUtils.getAllData("home_banner");
        while (data.moveToNext()) {
            banners.add(data.getString(0));
        }
        myPagerAdapter = new MyPagerAdapter(getContext());
        myPagerAdapter.setOnBannerClickListener(v -> {
            int position = (int) v.getTag();
            Toast.makeText(getContext(), "当前点击位置：" + position, Toast.LENGTH_SHORT).show();
        });
        //设置缓存页数
        viewPager.setOffscreenPageLimit(myPagerAdapter.getBanners().size() - 1);
        viewPager.setAdapter(myPagerAdapter);

        //添加页面更改监听器
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                //当新页面选中时调用此方法，position 为新选中页面的位置索引
                //在所选页面的时候,点点图片也要发生变化
                int selectItem = position % myPagerAdapter.getBanners().size();
                for (int i = 0; i < myPagerAdapter.getBanners().size(); i++) {
                    TextView textView = (TextView) viewGroup.getChildAt(i);
                    if (textView == null) return;
                    textView.setBackgroundResource(i == selectItem ? R.drawable.shape_swiper_point_selected : R.drawable.shape_swiper_point_unselected);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
//        initBannerPoint();
        //给ViewPager设置当前页，这样刚打开软件也能向左滑动
        currentItem = myPagerAdapter.getBanners().size() * 50;
        viewPager.setCurrentItem(currentItem);
    }

    public void initBannerPoint() {
        for (int j = 0; j < viewGroup.getChildCount(); j++) {
            viewGroup.removeView(viewGroup.getChildAt(j));
        }
        //将点点的图添加到视图ViewGroup中
        for (int i = 0; i < myPagerAdapter.getBanners().size(); i++) {
            TextView textView = new TextView(getContext());
            textView.setBackgroundResource(i == 0 ? R.drawable.shape_swiper_point_selected : R.drawable.shape_swiper_point_unselected);
            //设置图片的宽高 为10像素
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(40, 30);
            layoutParams.leftMargin = 15;
            layoutParams.rightMargin = 15;
            textView.setLayoutParams(layoutParams);
            viewGroup.addView(textView, layoutParams);
        }
    }

    public void initTabs() {
        tabLayout.addTab(tabLayout.newTab().setText("数字藏品"));
        tabLayout.addTab(tabLayout.newTab().setText("发售日历"));
        tabLayout.addTab(tabLayout.newTab().setText("盲盒精选"));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        loadingIsShow = false;
                        currentTitle = 0;
                        switchAdapter(0);
                        break;
                    case 1:
                        loadingIsShow = false;
                        currentTitle = 1;
                        switchAdapter(1);
                        break;
                    case 2:
                        loadingIsShow = false;
                        currentTitle = 2;
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void switchAdapter(int id) {
        if (id == 0) {
            homeListView1.setVisibility(View.GONE);
            homeListView.setVisibility(View.VISIBLE);
            if (collectionsList.size() == 0 || collectionsList == null) {
                System.out.println(321321321);
                initCollectionList(homeCollectionListAdapter);
            }
        }
        if (id == 1) {
            homeListView1.setVisibility(View.VISIBLE);
            homeListView.setVisibility(View.GONE);
            if (homeSaleCalendarAdapter == null)
                homeSaleCalendarAdapter = new HomeSaleCalendarAdapter(collectionCalendar, getContext());
            if (collectionCalendar.size() == 0 || collectionCalendar == null) {
                System.out.println("初始化");
                initCalendarList(homeSaleCalendarAdapter);
            }
            homeListView1.setAdapter(homeSaleCalendarAdapter);
            ListViewUtils.setListViewHeightBasedOnChildren(homeListView1);
        }

    }



    public void getBannerData() {
        List<String> bannerImg = new ArrayList<>();
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/banner/list");
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonRecords = jsonResponse.getJSONArray("value");
                for (int i = 0; i < jsonRecords.size(); i++) {
                    String banner = jsonRecords.getString(i);
                    //下载图片
                    HttpUtils.download(banner, "/data/data/" + getContext().getPackageName() + banner);
                    bannerImg.add("/data/data/" + getContext().getPackageName() + banner);
                }
                handler.post(() -> {
                    banners.clear();
                    banners.addAll(bannerImg);
                    myPagerAdapter.notifyDataSetChanged();
                    initBannerPoint();
                });
                if (!swiperInit) {
                    DBUtils.deleteAllData("home_banner");
                    DBUtils.insertHomeBannerData(bannerImg);
                    swiperInit = true;
                }
            } else {
                handler.post(() -> {
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    public void initCollectionList(BaseAdapter adapter) {
        System.out.println("执行");
        loadingIsShow = true;
        if (!collectionInit && DBUtils.getAllData("home_goods").getCount() > 0) {
            setHomeCollectionCache();
            loadingIsShow = false;
            return;
        }

        loading.setVisibility(View.VISIBLE);
        loadingIsShow = true;
        if (listFinish) {
            loading.setVisibility(View.GONE);
            loadingIsShow = false;
            return;
        }
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/home/collections/" + cListPageIndex + "/10");
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    Toast.makeText(getContext(), "服务器异常", Toast.LENGTH_SHORT).show();
                });
            } else if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonRecords = jsonResponse.getJSONArray("value");
                int size = jsonRecords.size();
                if (size == 0) {
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        loadingIsShow = false;
                        Toast.makeText(getContext(), "暂无可查询的藏品", Toast.LENGTH_SHORT).show();
                        listFinish = true;
                    });
                } else {
                    for (int i = 0; i < jsonRecords.size(); i++) {
                        JSONObject jsonGoods = jsonRecords.getJSONObject(i);
                        Collections collections = new Collections(
                                jsonGoods.getInteger("id"),
                                jsonGoods.getString("name"),
                                jsonGoods.getInteger("mintage"),
                                jsonGoods.getString("issuer"),
                                jsonGoods.getString("image"),
                                (float) jsonGoods.getInteger("price")
                        );
                        collectionsList.add(collections);
                    }
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        adapter.notifyDataSetChanged();
                        homeListView.setVisibility(View.VISIBLE);
                        loadingIsShow = false;
                        ListViewUtils.setListViewHeightBasedOnChildren(homeListView);
                    });
                    if (!collectionInit) {
                        collectionInit = true;
                        DBUtils.deleteAllData("home_goods");
                        DBUtils.insertHomeGoodsData(collectionsList);
                    }
                    if (size == 10) cListPageIndex++;
                    else listFinish = true;
                }
            } else {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    public void setHomeCollectionCache() {
        collectionsList.clear();
        Cursor cursor = DBUtils.getAllData("home_goods");
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            int mintage = cursor.getInt(2);
            String issuer = cursor.getString(3);
            String image = cursor.getString(4);
            Float price = cursor.getFloat(5);
            collectionsList.add(new Collections(id, name, mintage, issuer, image, price));
        }
        cursor.close();
        homeCollectionListAdapter.notifyDataSetChanged();
        loading.setVisibility(View.GONE);
        collectionInit = true;
        new Thread(() -> {
            DBUtils.deleteAllData("home_goods");
            List<Collections> collectionsList1 = DBUtils.updateHomeGoodsCache();
            handler.post(() -> {
                collectionsList.clear();
                collectionsList.addAll(collectionsList1);
                homeCollectionListAdapter.notifyDataSetChanged();
                cListPageIndex++;
                loadingIsShow = false;
                ListViewUtils.setListViewHeightBasedOnChildren(homeListView);
            });
            DBUtils.insertHomeGoodsData(collectionsList1);
        }).start();
    }

    public void initCalendarList(BaseAdapter baseAdapter) {
        loading.setVisibility(View.VISIBLE);
        loadingIsShow = true;
        if (calendarFinish) {
            loading.setVisibility(View.GONE);
            loadingIsShow = false;
            return;
        }
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/home/calendar/" + cCalendarPageIndex + "/10");
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    Toast.makeText(getContext(), "服务器异常", Toast.LENGTH_SHORT).show();
                });
            } else if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonRecords = jsonResponse.getJSONArray("value");
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                int size = jsonRecords.size();
                if (size == 0) {
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        loadingIsShow = false;
                        Toast.makeText(getContext(), "暂无可查询的藏品", Toast.LENGTH_SHORT).show();
                        calendarFinish = true;
                    });
                } else {
                    for (int i = 0; i < jsonRecords.size(); i++) {
                        JSONObject jsonGoods = jsonRecords.getJSONObject(i);
                        Collections collections = new Collections(
                                jsonGoods.getInteger("id"),
                                jsonGoods.getString("name"),
                                jsonGoods.getInteger("mintage"),
                                (float) jsonGoods.getInteger("price"),
                                LocalDateTime.parse(jsonGoods.getString("releaseDate"), df),
                                jsonGoods.getString("image")
                        );
                        collectionCalendar.add(collections);
                    }
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        baseAdapter.notifyDataSetChanged();
                        loadingIsShow = false;
                        ListViewUtils.setListViewHeightBasedOnChildren(homeListView1);
                    });
                    if (size == 10) cCalendarPageIndex++;
                    else calendarFinish = true;
                }
            } else {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    public void getNewNotice() {
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/article/NewContent/get/1");
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
                Toast.makeText(getContext(), "服务器异常", Toast.LENGTH_SHORT).show();
            }
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONObject res = jsonResponse.getJSONObject("value");
//                newNoticeId = jsonResponse.getInteger("value");
                handler.post(() -> {
                    newNoticeId = res.getInteger("id");
                    newNoticeText.setText(res.getString("title"));
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    public void getNewNews() {
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/article/NewContent/get/2");
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
                Toast.makeText(getContext(), "服务器异常", Toast.LENGTH_SHORT).show();
            }
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONObject res = jsonResponse.getJSONObject("value");
//                newNewsId = jsonResponse.getInteger("value");
                handler.post(() -> {
                    newNewsId = res.getInteger("id");
                    textNews.setText(res.getString("title"));
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }


}
